package com.shire.movienizerdroid.activity;

import java.lang.ref.WeakReference;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.shire.movienizerdroid.MovienizerDroidActivity;
import com.shire.movienizerdroid.R;
import com.shire.movienizerdroid.db.DataSource;
import com.shire.movienizerdroid.domain.Movie;
import com.shire.movienizerdroid.thirdparty.gesturefilter.SimpleGestureFilter;
import com.shire.movienizerdroid.thirdparty.gesturefilter.SimpleGestureListener;
import com.shire.movienizerdroid.thirdparty.imagezoom.PictureZoomActivity;
import com.shire.movienizerdroid.utils.CollectionUtils;
import com.shire.movienizerdroid.utils.Utils;

/**
 * @author yhernandezdiaz
 */
public class ViewMovieActivity extends Activity implements SimpleGestureListener {
	public static final String MOVIE_CODE_EXTRA = "movie";
	public static final String MOVIE_INDEX_EXTRA = "index";

	private SimpleGestureFilter detector;

	private Movie movie;
	private int movieIndex = -1;

	private WebView tvMovieDescription;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.viewmovie);

		detector = new SimpleGestureFilter(this, this);

		final Intent intent = getIntent();

		movie = DataSource.getInstance().getMovie(intent.getLongExtra(MOVIE_CODE_EXTRA, -1));
		movieIndex = intent.getIntExtra(MOVIE_INDEX_EXTRA, -1);

		tvMovieDescription = (WebView) findViewById(R.id.tvMovieDescription);
		tvMovieDescription.setWebViewClient(new DescriptionWebViewClient(this));
		tvMovieDescription.getSettings().setJavaScriptEnabled(true);

		showLongInfo(true);
	}

	private void showLongInfo(boolean truncDescription) {
		final StringBuilder sb = new StringBuilder();
		sb.append(getString(R.string.tpl_movie_info_top, movie.getTitle()));

		sb.append("<div id=\"coverc\">");
		sb.append("<a href=\"act:zoomCover\"><img id=\"cover\" src=\"" + Utils.getCoverThumbnailUrl(this, movie.getImagePath(), movie.getImageUrl()) + "\"/></a>");
		sb.append(String.format("<a href=\"%s\">IMDB</a>", movie.getIMDBSite()));
		sb.append("</div>");
		sb.append("<div class=\"tags\">");
		appendMovieTag(sb, Movie.COLUMN_IN_COLLECTION, getString(R.string.movie_in_collection), movie.isInCollection());
		appendMovieTag(sb, Movie.COLUMN_SEEN, getString(R.string.movie_seen), movie.isSeen());
		appendMovieTag(sb, Movie.COLUMN_WANTED, getString(R.string.movie_wanted), movie.isWanted());
		appendMovieTag(sb, Movie.COLUMN_FOR_SALE, getString(R.string.movie_for_sale), movie.isForSale());
		sb.append("</div>");

		sb.append("<div class=\"info\">");

		final String movieInfoFormat = getString(R.string.tpl_movie_info_format);

		sb.append(String.format(movieInfoFormat, getString(R.string.movie_genres), CollectionUtils.collectionToString(movie.getGenres(), " / ", "<a href=\"act:filter:genre:%1$s\">%1$s</a>")));
		sb.append(String.format(movieInfoFormat, getString(R.string.movie_year), String.format("<a href=\"act:filter:year:%1$d\">%1$d</a>", movie.getYear())));
		sb.append(String.format(movieInfoFormat, getString(R.string.movie_countries), CollectionUtils.collectionToString(movie.getCountries(), ", ")));
		final int h = movie.getDuration() / 60;
		final int m = movie.getDuration() % 60;
		sb.append(String.format(movieInfoFormat, getString(R.string.movie_duration), String.format("%d min. (%d:%s)", movie.getDuration(), h, (m < 10 ? "0" : "") + String.valueOf(m))));
		sb.append(String.format(movieInfoFormat, getString(R.string.movie_imdb_rating), movie.getIMDBRating()));
		sb.append(String.format(movieInfoFormat, getString(R.string.movie_user_rating), movie.getUserRating()));
		sb.append(String.format(movieInfoFormat, getString(R.string.movie_directors), CollectionUtils.collectionToString(movie.getDirectors(), ", ", "<a href='act:filter:director:\"%1$s\"'>%1$s</a>")));
		sb.append(String.format(movieInfoFormat, getString(R.string.movie_screenplay), CollectionUtils.collectionToString(movie.getScreenplay(), ", ")));
		sb.append(String.format(movieInfoFormat, getString(R.string.movie_composers), CollectionUtils.collectionToString(movie.getComposers(), ", ")));
		sb.append(String.format(movieInfoFormat, getString(R.string.movie_actors), CollectionUtils.collectionToString(movie.getActors(), ", ", "<a href='act:filter:actor:\"%1$s\"'>%1$s</a>", 10, ", ...")));
		sb.append(String.format(movieInfoFormat, getString(R.string.movie_slogan), movie.getTagline()));

		sb.append("<div>");
		if ((truncDescription) && (movie.getDescription().length() > 150))
			sb.append(movie.getDescription().substring(0, 150) + getString(R.string.movie_expand_description_link));
		else
			sb.append(movie.getDescription());
		sb.append("</div>");

		sb.append("</div>");
		sb.append(getString(R.string.tpl_movie_info_bottom));

		tvMovieDescription.loadDataWithBaseURL("fake://not/needed", sb.toString(), "text/html", "utf-8", "");
	}

	private static void appendMovieTag(StringBuilder sb, String tag, String desc, boolean on) {
		sb.append(String.format("<img src=\"file:///android_asset/%s_%s.png\" title=\"%s\" />", tag, on ? "on" : "off", desc));
	}

	@Override
	public boolean dispatchTouchEvent(MotionEvent me) {
		this.detector.onTouchEvent(me);
		return super.dispatchTouchEvent(me);
	}

	public void onSwipe(int direction) {
		if ((direction == SimpleGestureFilter.SWIPE_LEFT) || (direction == SimpleGestureFilter.SWIPE_RIGHT)) {
			final Cursor moviesCursor = DataSource.getInstance().getCurrentMoviesCursor();
			final int npos = movieIndex + ((direction == SimpleGestureFilter.SWIPE_LEFT) ? 1 : -1);
			if (npos >= 0 && npos < moviesCursor.getCount()) {
				moviesCursor.moveToPosition(npos);
				final Intent next = new Intent(this, ViewMovieActivity.class);
				next.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				next.putExtra(ViewMovieActivity.MOVIE_CODE_EXTRA, moviesCursor.getLong(0));
				next.putExtra(ViewMovieActivity.MOVIE_INDEX_EXTRA, npos);
				startActivity(next);
				finish();
				if (npos < movieIndex)
					overridePendingTransition(R.anim.slide_right_in, R.anim.slide_right_out);
				else
					overridePendingTransition(R.anim.slide_left_in, R.anim.slide_left_out);
			}
		}
	}

	private static final class DescriptionWebViewClient extends WebViewClient {
		private final WeakReference<ViewMovieActivity> parentActivity;

		public DescriptionWebViewClient(ViewMovieActivity parentActivity) {
			super();
			this.parentActivity = new WeakReference<ViewMovieActivity>(parentActivity);
		}

		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			if ("act:expand".equals(url)) {
				parentActivity.get().showLongInfo(false);
			} else if ("act:zoomCover".equals(url)) {
				if ((!TextUtils.isEmpty(parentActivity.get().movie.getImagePath()))) {
					final String fullPath = Utils.getCoverPath(parentActivity.get(), parentActivity.get().movie.getImagePath(), null);
					if (null != fullPath) {
						final Intent intent = new Intent(parentActivity.get(), PictureZoomActivity.class);
						intent.putExtra(PictureZoomActivity.FILE_PATH_EXTRA, fullPath);
						parentActivity.get().startActivity(intent);
					}
				}
			} else if (url.startsWith("act:filter:")) {
				final Intent intent = new Intent(parentActivity.get(), MovienizerDroidActivity.class);
				intent.putExtra(MovienizerDroidActivity.FILTER_EXTRA, url.substring(11).replaceAll("%22", "\"").replaceAll("%20", " "));
				parentActivity.get().startActivity(intent);
			} else {
				final Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
				parentActivity.get().startActivity(intent);
			}
			return true;
		}
	}

	public void onDoubleTap() {}
}
